package config

import (
    "os"

    "gopkg.in/yaml.v3"
)

// DeviceConfig 设备配置结构
type DeviceConfig struct {
    ID           int               `yaml:"id"`
    Type         string            `yaml:"type"`
    IP           string            `yaml:"ip"`
    Port         int               `yaml:"port"`
    SlaveID      byte              `yaml:"slave_id"`
    RegStart     uint16            `yaml:"reg_start"`
    RegCount     uint16            `yaml:"reg_count"`
    CoilStart    uint16            `yaml:"coil_start"`
    CoilCount    uint16            `yaml:"coil_count"`
    PollInterval int               `yaml:"poll_interval"`
    Timeout      int               `yaml:"timeout"`
    Params       map[string]string `yaml:"params"`
}

// Config 系统配置
type Config struct {
    Devices   []DeviceConfig `yaml:"devices"`
    PluginDir string         `yaml:"plugin_dir"`
}

// Load 从文件加载配置
func Load(path string) (*Config, error) {
    data, err := os.ReadFile(path)
    if err != nil {
        return nil, err
    }

    var cfg Config
    if err := yaml.Unmarshal(data, &cfg); err != nil {
        return nil, err
    }

    // 设置默认值
    if cfg.PluginDir == "" {
        cfg.PluginDir = "./plugins"
    }

    for i := range cfg.Devices {
        dev := &cfg.Devices[i]
        if dev.PollInterval <= 0 {
            dev.PollInterval = 1
        }
        if dev.Timeout <= 0 {
            dev.Timeout = 1
        }
        if dev.SlaveID <= 0 {
            dev.SlaveID = 1
        }
        if dev.RegCount <= 0 {
            dev.RegCount = 10
        }
        if dev.CoilCount <= 0 {
            dev.CoilCount = 10
        }
    }

    return &cfg, nil
}
